package com.luych.toolbox.common.event.base.service.publisher;

import com.luych.toolbox.common.event.base.service.WebSocketLetterRemoteApplicationEvent;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketLetter;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;

import java.util.UUID;

public class WebSocketLetterPublisher {

    private final BusProperties busProperties;
    private final ApplicationEventPublisher applicationEventPublisher;

    public WebSocketLetterPublisher(BusProperties busProperties, ApplicationEventPublisher applicationEventPublisher) {
        this.busProperties = busProperties;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void info(String userId, String message, String content) {
        String id = UUID.randomUUID().toString();
        WebSocketLetter letter = new WebSocketLetter(id, WebSocketLetter.Type.INFO, message, content);
        this.send(userId, letter);
    }

    public void warn(String userId, String message, String content) {
        String id = UUID.randomUUID().toString();
        WebSocketLetter letter = new WebSocketLetter(id, WebSocketLetter.Type.WARN, message, content);
        this.send(userId, letter);
    }

    public void error(String userId, String message, String content) {
        String id = UUID.randomUUID().toString();
        WebSocketLetter letter = new WebSocketLetter(id, WebSocketLetter.Type.ERROR, message, content);
        this.send(userId, letter);
    }

    public void success(String userId, String message, String content) {
        String id = UUID.randomUUID().toString();
        WebSocketLetter letter = new WebSocketLetter(id, WebSocketLetter.Type.SUCCESS, message, content);
        this.send(userId, letter);
    }

    public void send(String userId, WebSocketLetter.Type type, String message, String content, Object data) {
        String id = UUID.randomUUID().toString();
        WebSocketLetter letter = new WebSocketLetter(id, type, message, content);
        letter.setData(data);
        this.send(userId, letter);
    }

    public void send(String userId, WebSocketLetter.Type type, String message, String content) {
        String id = UUID.randomUUID().toString();
        WebSocketLetter letter = new WebSocketLetter(id, type, message, content);
        this.send(userId, letter);
    }

    public void send(String userId, WebSocketLetter letter) {
        WebSocketLetterRemoteApplicationEvent event = new WebSocketLetterRemoteApplicationEvent(busProperties.getId(), "**", userId, letter);
        applicationEventPublisher.publishEvent(event);
    }
}
